package org.zk.controller;

import com.google.gson.Gson;
import org.zk.entity.Purse;
import org.zk.entity.User;
import org.zk.entity.UserExt;
import org.zk.service.PurseService;
import org.zk.service.UserService;
import org.zk.util.Msg;
import org.zk.util.UtilDate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;


@Controller
@RequestMapping(value = "/user")
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private PurseService purseService;

    Gson gson = new Gson();

    /**
     * 接口2：用户注册
     *
     * @param registUser
     * @return
     */
    //三种状态 成功：1，失败：0，已经注册过了：2
    @ResponseBody
    @Transactional
    @RequestMapping(value = "/doRegist", method = {RequestMethod.POST}, produces = "text/plain;charset=utf-8")
    public String doRegist(User registUser) {

        Msg msg = new Msg();
        String createDateStr = UtilDate.getCurrentDateStr();
//      设置创建日期
        registUser.setCreateAt(createDateStr);
        registUser.setGoodsNum(0);
        registUser.setPower(100);   //信用分
        registUser.setStatus((byte) 1);

        int registRst = userService.registUser(registUser);

        if (registRst == 2) {
            msg.setCode(2);
            return gson.toJson(msg);
        }

        Purse purse = new Purse();
        purse.setUserId(registUser.getId());
        purse.setBalance(0f);
        Integer addPurseRst = purseService.addPurse(purse);
        if (registRst == 1 && addPurseRst == 1) {
            msg.setCode(1);
        }
        return gson.toJson(msg);


//      注册成功创建一个钱包Purse 在service层处理


    }

    /**
     * 接口3：用户登录
     *
     * @param loginUser
     * @param request
     * @return
     */
    //登录状态 1.登录成功 0登陆失败
    @ResponseBody
    @RequestMapping(value = "/doLogin", method = {RequestMethod.POST})
    public String doLogin(User loginUser, HttpServletRequest request) {


        Msg msg = new Msg(0);
        User currentUser = userService.login(loginUser.getPhone(), loginUser.getPassword());
        if (currentUser != null) {
            msg.setCode(1);
            //登录成功加入session
            request.getSession().setAttribute("currentUser", currentUser);
        }
        return gson.toJson(msg);
    }

    /**
     * 用户退出登录（登录状态）
     *
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/nologin", method = {RequestMethod.GET, RequestMethod.POST})
    public String noLogin(HttpServletRequest request) {

        Msg msg = new Msg(0);

        User currentUser = (User) request.getSession().getAttribute("currentUser");

        if (currentUser != null) {
            request.getSession().setAttribute("currentUser", null);
            msg.setCode(1);
            return gson.toJson(msg);
        } else {
            msg.setMessage("loginout state");
            return gson.toJson(msg);
        }

    }

    /**
     * 接口9：加载个人信息 (登录后状态)
     *(更新数据库后user属性不变是因为一直用的currentUser对象当然没有改变)
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/getPeoInfos", method = {RequestMethod.GET, RequestMethod.POST}, produces = "text/plain;charset=utf-8")
    public String getPeoInfos(HttpServletRequest request) {

        Msg msg = new Msg(0);
        User currentUser = (User) request.getSession().getAttribute("currentUser");

        if (currentUser != null) {

            UserExt userExt = new UserExt(currentUser);
            Purse purse = purseService.getByUid(currentUser.getId());
            userExt.setBalance(purse.getBalance());

            msg.setCode(1);
            msg.setData(userExt);
        }
        return gson.toJson(msg);

    }

    /**
     * 修改个人信息（登录状态）
     * （用的一直是currentUser对象 所以修改之后session里的对象也得更新）
     *
     * @param request
     * @param username
     * @param qq
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/changePeoInfos", method = {RequestMethod.POST})
    public String changePeoInfos(HttpServletRequest request, @RequestParam("username") String username, @RequestParam("qq") String qq) {

        Msg msg = new Msg(0);
        User currentUser = (User) request.getSession().getAttribute("currentUser");
        if (currentUser == null) {
            msg.setMessage("loginout state");
            return gson.toJson(msg);
        }
        Integer num = userService.chageUserInfo(currentUser.getId(), username, qq);
        if (num > 0) {

            //修改成功 则同时更新session里的currentUser值
            User alterCurrentUser = userService.getUserByUid(currentUser.getId());
            if(alterCurrentUser!=null){
                request.getSession().setAttribute("currentUser", alterCurrentUser);
            }
            msg.setCode(1);
        }
        return gson.toJson(msg);
    }


}
